package com.qiyang.lambda;

import java.util.ArrayList;
import java.util.List;
import java.util.function.*;

class Dog {

    private String name = "哮天犬";

    private int food = 10;

    /**
     * 狗叫，静态方法
     *
     * @param dog
     */
    protected static void bark(Dog dog) {
        System.out.println(dog + "叫了");
    }

    @Override
    public String toString() {
        return this.name;
    }

    /**
     * 注意：Dog this参数,JDK默认会把当前实例传入到非静态方法，参数名即为this，位置是第一个
     *
     * @param num
     * @return 还剩多少斤
     */
    public int eat(Dog this, int num) {
        System.out.println("吃狗粮" + num + "斤");
        this.food -= num;
        return this.food;
    }

    public Dog(){

    }

    /**
     * 带参数的构造函数
     * @param name
     */
    public Dog(String name) {
        this.name = name;
    }
}

/**
 * Created on 2018/8/4.
 *
 * @author sehuaqi.
 * 描述：
 */
public class MethodRefrenceDemo {

    public static void main(String args[]) {
        //执行函数

        //方法引用 ::
//        Consumer<String> consumer = s -> System.out.println(s);
        Consumer<String> consumer = System.out::println;
        consumer.accept("我是需要输出的内容");

        //静态方法的方法应用
        Consumer<Dog> consumer2 = Dog::bark;
        consumer2.accept(new Dog());


        //非静态方法，使用对象实例来引用
        Dog dog = new Dog();
//        Function<Integer, Integer> function = dog::eat;

        //可以换成一元函数
        UnaryOperator<Integer> function = dog::eat;
        IntUnaryOperator function2 = dog::eat;

        System.out.println("还剩" + function.apply(3) + "斤");
        System.out.println("还剩" + function2.applyAsInt(3) + "斤");

        //使用类名来做方法引用
        BiFunction<Dog, Integer, Integer> eatFunction = Dog::eat;
        System.out.println("还剩" + eatFunction.apply(dog, 1) + "斤");

        //构造函数的方法引用
        Supplier<Dog> supplier = Dog::new;
        System.out.println("创建了新的对象：" + supplier.get());

        //带参数的构造方法引用
        Function<String, Dog> function1 = Dog::new;
        System.out.println("创建了新的对象：" + function1.apply("泰迪"));

        List list = new ArrayList();
        list.add("qiyang");
        list.add("qisehua");
        changeList(list);
        System.out.println(list);

    }

    /**
     * 传值引用
     * @param list
     */
    private static void changeList(List<String> list){
        list.add("xiaokeai");
        list = new ArrayList<>();
        list.add("qisehua");
    }

}
